package web.filter;
/*
 * User: key
 * ClassName:${NAME}
 * Date: 2023/5/6
 * Time: 13:09
 * description:
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(filterName = "Filter01_Charset",value = "/*")
public class Filter01_Charset implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取request作用域中的uri值
        String uri = req.getRequestURI();
        //判断uri中不含有特定后缀则进行转码
        if(check(uri)){
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
        }
        //进行过滤
        chain.doFilter(req, resp);
    }
    public boolean check(String path){
        List<String> list = Arrays.asList(".html",".css",".js","/","png");
        for (String s : list) {
            if(path.endsWith(s)){
                return false;
            }
        }
        return true;
    }
}
